<template>
  <div class="user-mng">
    <h2>用户管理</h2>
    <div v-if="message" style="color: #f56c6c; margin: 10px 0;">{{ message }}</div>
    <table class="user-table">
      <thead>
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>手机号</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="user in users" :key="user.userId">
        <td>{{ user.userId }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.phone }}</td>


      </tr>
      </tbody>
    </table>
    <!-- 分页控件 -->
    <div class="pagination">
      <button :disabled="pageNum === 1" @click="changePage(pageNum-1)">上一页</button>
      <span>第 {{ pageNum }} 页</span>
      <button :disabled="!hasNextPage" @click="changePage(pageNum+1)">下一页</button>
    </div>
    <!-- 添加用户弹窗 -->
    <div v-if="showAdd" class="dialog-mask" @click.self="cancel">
      <div class="dialog">
        <h3>添加用户</h3>
        <input v-model="form.username" placeholder="请输入用户名" />
        <input v-model="form.phone" placeholder="请输入手机号" />
        <input v-model="form.password" placeholder="请输入密码" type="password" />
        <div class="dialog-btns">
          <button @click="saveUser">保存</button>
          <button @click="cancel">取消</button>
        </div>
      </div>
    </div>
    <!-- 修改用户弹窗 -->
<!--    <div v-if="showEdit" class="dialog-mask" @click.self="cancel">-->
<!--      <div class="dialog">-->
<!--        <h3>修改用户</h3>-->
<!--        <input v-model="form.username" placeholder="请输入用户名" />-->
<!--        <input v-model="form.phone" placeholder="请输入手机号" />-->
<!--        <div class="dialog-btns">-->
<!--          <button @click="saveUser">保存</button>-->
<!--          <button @click="cancel">取消</button>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
    <!-- 头像上传弹窗 -->
<!--    <div v-if="showAvatarDialog" class="dialog-mask" @click.self="closeAvatarDialog">-->
<!--      <div class="dialog">-->
<!--        <h3>上传头像</h3>-->
<!--        <input type="file" accept="image/*" @change="onAvatarChange" />-->
<!--        <div v-if="avatarPreview" style="margin-top:16px;text-align:center;">-->
<!--          <img :src="avatarPreview" alt="头像预览" style="width:80px;height:80px;border-radius:50%;" />-->
<!--        </div>-->
<!--        <div class="dialog-btns">-->
<!--          <button @click="saveAvatar">保存</button>-->
<!--          <button @click="closeAvatarDialog">取消</button>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 分页相关数据
const users = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const hasNextPage = ref(false)

const showAdd = ref(false)
const showEdit = ref(false)
const form = ref({ userId: null, username: '', phone: '', password: '' })

const message = ref('') // 用于简单的操作提示

// 头像上传相关
const showAvatarDialog = ref(false)
const avatarPreview = ref('')
const currentAvatarUser = ref(null)
const avatarFile = ref(null)

function openAvatarDialog(user) {
  showAvatarDialog.value = true
  currentAvatarUser.value = user
  avatarPreview.value = user.avatar || ''
  avatarFile.value = null
}
function closeAvatarDialog() {
  showAvatarDialog.value = false
  avatarPreview.value = ''
  currentAvatarUser.value = null
  avatarFile.value = null
}
function onAvatarChange(e) {
  const file = e.target.files[0]
  if (file) {
    avatarPreview.value = URL.createObjectURL(file)
    avatarFile.value = file
  }
}
async function saveAvatar() {
  if (!avatarFile.value) {
    message.value = '请选择图片文件！'
    return
  }
  // 构造form-data上传图片
  const formData = new FormData()
  formData.append('multipartFile', avatarFile.value)
  try {
    const res = await fetch('http://localhost:8082/file/upload', {
      method: 'POST',
      body: formData
    })
    const data = await res.json()
    if (data.code === 200) {
      // 上传成功后，调用用户修改接口保存头像
      const avatarUrl = data.data // 假设后端返回图片url
      if (currentAvatarUser.value) {
        await fetch('/api/user/users/update', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            userId: currentAvatarUser.value.userId,
            avatar: avatarUrl
          })
        })
        message.value = '头像上传并保存成功！'
        fetchUsers() // 刷新用户列表
      }
    } else {
      message.value = data.msg || '上传失败！'
    }
  } catch (e) {
    message.value = '上传请求失败！'
  }
  closeAvatarDialog()
}

// 获取用户分页数据
async function fetchUsers() {
  const res = await fetch(`/api/user/users/list?page=${pageNum.value}&size=${pageSize.value}`)
  const data = await res.json()
  users.value = data.data?.users || []
  hasNextPage.value = (pageNum.value * pageSize.value) < (data.data?.total || 0)
}

onMounted(fetchUsers)

function changePage(newPage) {
  pageNum.value = newPage
  fetchUsers()
}

// 添加或修改用户
async function saveUser() {
  try {
    if (showAdd.value) {
      // 添加用户
      const res = await fetch('/api/user/users/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          username: form.value.username,
          password: form.value.password,
          phone: form.value.phone
        })
      })
      const data = await res.json()
      if (data.code === 200) {
        message.value = '添加成功！'
        fetchUsers()
      } else {
        message.value = data.msg || '添加失败！'
      }
    } else if (showEdit.value) {
      // 修改用户
      const res = await fetch('api/user/users/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: form.value.userId,
          username: form.value.username,
          phone: form.value.phone
        })
      })
      const data = await res.json()
      if (data.code === 200) {
        message.value = '修改成功！'
        fetchUsers()
      } else {
        message.value = data.msg || '修改失败！'
      }
    }
  } catch (e) {
    message.value = '请求失败！'
  }
  cancel()
}

// 编辑用户
function editUser(user) {
  form.value = { ...user, password: '' }
  showEdit.value = true
  showAdd.value = false
}

// 删除用户
async function deleteUser(id) {
  if (!confirm('确定要删除该用户吗？')) return
  try {
    const res = await fetch(`/api/user/users/delete/${id}`, {
      method: 'DELETE'
    })
    const data = await res.json()
    if (data.code === 200) {
      message.value = '删除成功！'
      fetchUsers()
    } else {
      message.value = data.msg || '删除失败！'
    }
  } catch (e) {
    message.value = '请求失败！'
  }
}

// 取消操作
function cancel() {
  showAdd.value = false
  showEdit.value = false
  form.value = { userId: null, username: '', phone: '', password: '' }
}
</script>

<style scoped>
.user-mng {
  max-width: 1200px;   /* 原来是800px，改大一点 */
  margin: 30px auto;
  background: #fff;
  padding: 40px;       /* 内边距也可以适当加大 */
  border-radius: 10px;
  box-shadow: 0 2px 8px #eee;
}
.user-table { width: 100%; border-collapse: collapse; margin-top: 16px; }
.user-table th, .user-table td { border: 1px solid #eee; padding: 8px; text-align: center; }
.add-btn, .edit-btn, .del-btn { margin: 0 4px; padding: 4px 12px; border: none; border-radius: 4px; cursor: pointer; }
.add-btn { background: #409eff; color: #fff; }
.edit-btn { background: #67c23a; color: #fff; }
.del-btn { background: #f56c6c; color: #fff; }
.pagination { margin: 16px 0; text-align: center; }
.pagination button { margin: 0 8px; padding: 4px 12px; border-radius: 4px; border: none; background: #409eff; color: #fff; cursor: pointer; }
.pagination button:disabled { background: #ccc; cursor: not-allowed; }
.dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.dialog {
  background: #fff;
  padding: 32px 40px;
  border-radius: 10px;
  min-width: 320px;
  box-shadow: 0 2px 16px #bbb;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.dialog-btns {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
}
</style>
